from src.core import log
from src.utils.deep import get_os_info
from src.core.variables.constant import *
from src.core.variables.function import *
from .library.manage import db_manager as dbm


class _DB:
    class hosting:
        from src.db.library.hosting import (
            Team_info,
            Team_user,
            Project_info,
            Project_user,
            Module_info,
        )

    class sys_default:
        from src.db.library.sys_default import User, Role, Node, Function

    class hosting_Java:
        from src.db.library.hosting_Java import (
            App,
            C_records,
            Run_records,
            Deploy_records,
            Resource_usage_records,
            App_backup,
        )

    class hosting_Static:
        from src.db.library.hosting_Static import (
            App,
            App_backup,
            C_records,
            Run_records,
            Deploy_records,
            Resource_usage_records,
        )

    # class middleware:
    #     pass

    # class system:
    #     pass


dbs = _DB()
for i in DATABASE.DATABASE_LIST:
    dbm.add_database(
        db_name=i, db_path=f"{DATABASE.DATABASE_PATH}/{i}.db", db_obj=getattr(dbs, i)
    )
    dbm.create_tables(db_name=i)


# 初始化管理员角色
with dbm.get("sys_default") as db_session:
    from sqlalchemy.orm import scoped_session

    db_session: scoped_session
    db_result = (
        db_session.query(dbs.sys_default.Role)
        .filter(dbs.sys_default.Role.name == "admin")
        .all()
    )
    if len(db_result) == 0:
        admin_role = {
            "uid": CREATE_ID(),
            "name": "admin",
            "description": "管理员",
            "status": "1",
            "create_user": "system",
            "update_user": "system",
            "create_time": get_os_info().local_time("no week"),
            "update_time": get_os_info().local_time("no week"),
        }
        db_session.add(dbs.sys_default.Role(**admin_role))
        if dbm.commit(db_session):
            log.INFO("管理员角色初始化成功！")
        else:
            log.CRITICAL("无法初始化管理员角色！")

# 初始化普通用户角色
with dbm.get("sys_default") as db_session:
    from sqlalchemy.orm import scoped_session

    db_session: scoped_session
    db_result = (
        db_session.query(dbs.sys_default.Role)
        .filter(dbs.sys_default.Role.name == "user")
        .all()
    )
    if len(db_result) == 0:
        user_role = {
            "uid": CREATE_ID(),
            "name": "user",
            "description": "普通用户",
            "status": "1",
            "create_user": "system",
            "update_user": "system",
            "create_time": get_os_info().local_time("no week"),
            "update_time": get_os_info().local_time("no week"),
        }
        db_session.add(dbs.sys_default.Role(**user_role))
        if dbm.commit(db_session):
            log.INFO("普通用户角色初始化成功！")
        else:
            log.CRITICAL("无法初始化默认角色！")


# 初始化管理员用户
with dbm.get("sys_default") as db_session:
    from sqlalchemy.orm import scoped_session

    db_session: scoped_session
    db_result = (
        db_session.query(dbs.sys_default.User)
        .filter(dbs.sys_default.User.username == "fmadmin")
        .all()
    )
    if len(db_result) == 0:
        admin_user = {
            "uid": CREATE_ID(),
            "username": "fmadmin",
            "password": ENCRYPTION("Fmadmin!@#456"),
            "email": "",
            "phone": "",
            "roles": '["admin"]',
            "create_time": get_os_info().local_time("no week"),
            "update_time": get_os_info().local_time("no week"),
            "last_login_time": get_os_info().local_time("no week"),
            "last_login_ip": "",
            "login_count": "0",
        }
        db_session.add(dbs.sys_default.User(**admin_user))
        if dbm.commit(db_session):
            log.INFO("管理员：<fmadmin>用户初始化成功，请登录后修改密码！")
        else:
            log.CRITICAL("无法初始化管理员用户！")
    elif len(db_result) > 1:
        log.CRITICAL("数据库中存在多个管理员用户，请检查数据库！")
        raise ValueError("数据库中存在多个管理员用户，请检查数据库。")


# 初始化管理员用户
with dbm.get("sys_default") as db_session:
    from sqlalchemy.orm import scoped_session

    db_session: scoped_session
    db_result = (
        db_session.query(dbs.sys_default.User)
        .filter(dbs.sys_default.User.username == "multi_nodes")
        .all()
    )
    if len(db_result) == 0:
        multi_nodes_user = {
            "uid": CREATE_ID(),
            "username": "multi_nodes",
            "password": ENCRYPTION(CREATE_ID()),
            "email": "",
            "phone": "",
            "roles": '["admin"]',
            "create_time": get_os_info().local_time("no week"),
            "update_time": get_os_info().local_time("no week"),
            "last_login_time": get_os_info().local_time("no week"),
            "last_login_ip": "",
            "login_count": "0",
        }
        db_session.add(dbs.sys_default.User(**multi_nodes_user))
        if dbm.commit(db_session):
            log.INFO("管理员：<multi_nodes>用户初始化成功，请登录后修改密码！")
        else:
            log.CRITICAL("无法初始化管理员用户！")
    elif len(db_result) > 1:
        log.CRITICAL("数据库中存在多个管理员用户，请检查数据库！")
        raise ValueError("数据库中存在多个管理员用户，请检查数据库。")


# 初始化功能数据库
with dbm.get("sys_default") as db_session:
    from sqlalchemy.orm import scoped_session

    db_session: scoped_session
    db_result = (
        db_session.query(dbs.sys_default.Function)
        .filter(dbs.sys_default.Function.name == "multi_node")
        .all()
    )
    if len(db_result) == 0:
        db_session.add(
            dbs.sys_default.Function(
                uid=CREATE_ID(), name="multi_node", status="disbale", is_tip="0"
            )
        )
        log.INFO(f"初始化功能：multi_node 数据配置到数据库...")
    elif len(db_result) > 1:
        db_session.query(dbs.sys_default.Function).filter(
            dbs.sys_default.Function.name == "multi_node"
        ).delete()
        db_session.add(
            dbs.sys_default.Function(
                uid=CREATE_ID(), name="multi_node", status="disbale", is_tip="1"
            )
        )
        log.WARNING("数据库中功能数据有误，已经重置了功能状态！")
    if dbm.commit(db_session):
        log.INFO(f"功能初始化到数据库成功！")
    else:
        db_session.rollback()
        log.ERROR(f"功能初始化到数据库失败！")
